<template>
  <div class="register_module bgc1">
    <el-card class="form_module" style="max-width: 480px">
      <!-- 注册账号 -->
      <div class="wfull flex justify_center mb22 font_size_22 font_weight_bold">
        {{ $t("register_form_register_title") }}
      </div>
      <el-form
        :model="form"
        :rules="rules"
        label-width="auto"
        style="max-width: 600px"
        ref="ruleFormRef"
      >
        <!-- 手机号 -->
        <el-form-item prop="phoneNum">
          <div class="form_item wfull">
            <el-input
              class="form_item_input"
              v-model="form.phoneNum"
              :placeholder="$t('register_form_register_phone_placeholder')"
            >
              <template #prepend>+86</template>
            </el-input>
          </div>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="verificationCode">
          <div class="form_item wfull flex justify_between">
            <div class="flex4">
              <el-input
                class="form_item_input"
                type="text"
                :placeholder="
                  $t('register_form_register_verificationCode_placeholder')
                "
                v-model="form.verificationCode"
              />
            </div>
            <div>
              <el-button
                class="form_item_input"
                :disabled="countdownInfo.isDisabled"
                @click="getVericaTime"
                >{{ countdownInfo.buttonName }}</el-button
              >
            </div>
          </div>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password1">
          <div class="form_item wfull">
            <div class="form_item_input">
              <passwordInput v-model="form.password1" :showPrependIcon="false"></passwordInput>
            </div>
          </div>
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item prop="password2">
          <div class="form_item wfull">
            <div class="form_item_input">
              <passwordInput v-model="form.password2" :showPrependIcon="false" placeholderKey="register_form_register_password2Rule1"></passwordInput>
            </div>
          </div>
        </el-form-item>
        <!-- 底部按钮 -->
        <el-form-item>
          <div class="form_item wfull flex justify_around align_items_center">
            <el-button
              type="primary"
              class="flex3 h40"
              @click="handleRegister(ruleFormRef)"
              :loading="registerLoading"
              >{{ $t("register_form_register_btn") }}</el-button
            >
            <span
              class="flex2 text-align-c pointer logExisting_account"
              @click="handleLogin"
              >{{ $t("register_form_register_logExistingAccount_btn") }}</span
            >
            <span class="flex1 text-align-r pointer">{{
              $t("register_form_register_onlineService _btn")
            }}</span>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="bottom_tips font_size_12">
      {{ $t("register_form_register_bottom_tip_info") }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onBeforeUnmount, onMounted } from "vue";
import passwordInput from "@/components/passwordInput/passwordInput.vue"
import {
  RouleForm,
  RouleFormData,
  countdownData,
} from "../../viewModel/registerViewModel";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

const { t } = useI18n();


// 表单数据
onMounted(() => {
  let localCountdownInfo = JSON.parse(
    localStorage.getItem("countdownInfo") as string
  );
  if (localCountdownInfo) {
    countdownInfo.value = localCountdownInfo;
    if (countdownInfo.value.second !== 60) {
      getVericaTime();
    }
  }
});

const form = reactive<RouleForm>({
  phoneNum: "",
  verificationCode: "",
  password1: "",
  password2: "",
});

// 表单规则
const rules = reactive<FormRules<RouleForm>>(RouleFormData);
const ruleFormRef = ref<FormInstance>();

// 倒计时信息
let countdownInfo = ref(countdownData);

// 注册按钮loading
const registerLoading = ref<boolean>(false);

const router = useRouter();

// 定义倒计时函数
const getVericaTime = () => {
  countdownInfo.value.isDisabled = true;
  // 开始倒计时
  let interval = window.setInterval(function () {
    countdownInfo.value.buttonName = `${countdownInfo.value.second}${t(
      "register_form_register_remaining_reacquired"
    )}`;
    countdownInfo.value.second = countdownInfo.value.second - 1;
    if (countdownInfo.value.second <= 0) {
      countdownInfo.value.buttonName = t(
        "register_form_register_verificationCode_btn"
      );
      countdownInfo.value.second = 60;
      countdownInfo.value.isDisabled = false;
      window.clearInterval(interval);
    }
  }, 1000); // 一秒执行一次
};

// 注册事件
const handleRegister = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!", form);
      registerLoading.value = true;
      setTimeout(() => {
        registerLoading.value = false;
        handleLogin();
      }, 2000);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 跳转到登录页面

const handleLogin = () => {
  router.push({
    path: "/login",
  });
};

// 监听第一次输入密码内容，并保持用于和确认密码对比
watch(
  () => form.password1,
  (newVal) => {
    localStorage.setItem("password1", newVal);
  },
  {
    immediate: true,
  }
);

// 监听对象，数据是否发生变化，改变就进行重新保存
watch(
  countdownInfo,
  (newVal) => {
    let JSONSTR = JSON.stringify(newVal);
    localStorage.setItem("countdownInfo", JSONSTR);
  },
  {
    deep: true, // 深度监听
  }
);

// 页面即将销毁
// 清空密码缓冲
onBeforeUnmount(() => {
  localStorage.removeItem("password1");
});

console.log(ruleFormRef);
</script>
<style scoped>
.register_module {
  position: relative;
  height: 100vh;
  width: 100%;
}
.form_module {
  position: fixed;
  min-width: 500px;
  top: 50%;
  left: 70%;
  transform: translate(0, -50%);
}
.form_item {
  height: 55px;
  line-height: 55px;
}
.form_item_input {
  height: 40px;
}
.logExisting_account {
  color: #1890ff;
}
.bottom_tips {
  position: absolute;
  width: 100%;
  bottom: 30px;
  text-align: center;
  color: #ffffff;
}
</style>
